/**
 *  created by lllwx
 *  Date: 2021/6/1
 *  Time: 11:12 上午
 *  Version: 1.0
 *  For:
 */

import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';

dayjs.extend(duration);

/**
 * @desc 对日期进行标准格式化
 * @author lllwx
 * @date 2021/6/1 11:13 上午
 * @param {string | Date} date 日期对象 或 时间字符串
 * @param {string} format 格式化标准
 * @return {string}
 */
export function formatTime(date, format) {
  const baseFormat = 'YYYY-MM-DD HH:mm:ss';
  if (!date) return '';
  return dayjs(date).format(format || baseFormat);
}

/**
 * @desc 下载拼接url
 * @author lllwx
 * @date 2021/6/10 11:53 下午
 * @param {string} uri 连接
 * @param {string} key 参数字段
 * @param {string | number | Array } value 参数值
 * @return {string}
 */
function addParam(uri, key, value) {
  if (!value) {
    return uri;
  }
  const re = new RegExp(`([?&])${key}=.*?(&|$)`, 'i');
  const separator = uri.indexOf('?') !== -1 ? '&' : '?';
  let keyValueStr = `${key}=${value}`;
  // 数组参数处理
  if (value instanceof Array) {
    keyValueStr = '';
    value.forEach((_) => {
      keyValueStr = `${keyValueStr}${key}=${_}&`;
    });
  }
  if (uri.match(re)) {
    return uri.replace(re, `$1${keyValueStr}$2`);
  }
  return `${uri + separator + keyValueStr}`;

}

/**
 * @desc a标签下载文件
 * @author lllwx
 * @date 2021/6/10 11:53 下午
 * @param {string} request 请求url
 * @param {object} params 参数
 * @return
 */
export function downloadFile(request, params = {}) {
  const a = document.createElement('a');
  let url = `${process.env.VUE_APP_BASE_URL}${request}`;
  Object.keys(params).forEach((i) => {
    url = addParam(url, i, params[i]);
  });
  a.href = url;
  console.log(url);
  a.click();
}

/**
 * @desc 获取uuid
 * @author lllwx
 * @date 2021/6/1 11:13 上午
 * @return { string }
 */
export function guid() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }

  return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4();
}

// 合并
export function deepMerge(src, target) {
  Object.keys(target).forEach((key) => {
    src[key] = src[key] && src[key].toString() === '[object Object]'
      ? deepMerge(src[key], target[key])
      : (src[key] = target[key]);
  });
  return src;
}

/**
 * 业务常量的使用方式扩展
 * @param {Array} source
 * @returns {Function} fn
 fn() ===> source
 fn(value) ===> label
 fn(name) ===> value
 */
export default function createEnum(source = []) {
  const sourceMap = new Map();
  source.forEach((item) => {
    sourceMap.set(item.name, item.value);
    sourceMap.set(item.value, item.label);
  });

  // eslint-disable-next-line func-names
  return function (key) {
    if (key) {
      return sourceMap.get(key);
    }
    return source;
  };
}
